<template>
  <div class="page" style="padding-bottom: 80px;">
    <div>
      <nav-bar @change="navChange" :value="navTypeCurrent"></nav-bar>
    </div>

    <div v-if="navType == 'unpublished' && documents.length > 0" class="pdt-l">
      <div class="bd-l-main pdl-m">草稿箱</div>
      <div class="weui-cells weui-cells_after-title mgb-s v-mdl">
        <div v-for="(n, i) in documents" :key="i"
          @tap="onModify(n)"
          class="weui-cell weui-cell_access"
          hover-class="weui-cell_active">
          <div class="weui-cell__bd">
            <div>{{n.name}}</div>
            <div class="c-gray fs-5" style="padding-top: 16px;">最后更新时间：{{n.updatedAtName}}</div>
          </div>
        </div>
      </div>
    </div>

    <div v-for="(n, i) in dateTasks" :key="i">
      <div class="mgt-l pdl-m bd-l-main" v-if="navTypeCurrent==0">{{i}}</div>
      <div class="mgt-l pdl-m bd-l-main" v-if="navTypeCurrent>0">{{i}}发送</div>
      <div class="weui-cells weui-cells_after-title mgb-s v-mdl">
        <div v-for="(nn, ii) in n" :key="nn.id" @tap="goTaskProgresses(nn)" class="weui-cell weui-cell_access" hover-class="weui-cell_active">
          <div class="weui-cell__bd">
            <div class="cf">
              <div class="fl w85">
                <span class="block-ellipsis" v-if="nn.document && nn.document.name">{{nn.document.name}}</span>
              </div>
              <div v-if="nn.unreadCount" class="fr tag-msg" style="margin-top:6rpx;">
                {{nn.unreadCount}}
              </div>
            </div>
            <div class="cf fs-5 c-gray" style="padding-top: 8px;">
              <div class="fl w30" v-if="nn.group">
                <span class="block-ellipsis" v-if="nn.group.name">{{nn.group.name}}</span>
                <span v-else><open-data type="groupName" :open-gid="nn.group.openGroupId"></open-data></span>
              </div>
              <div class="fl mgl-10">
                <span>截止时间：{{nn.expireAtName || '无'}}</span>
              </div>
              <div class="fr">
                <span v-if="!nn.isPublished && nn.prePublishAtName">当日{{nn.prePublishAtName}}布置</span>
                <span v-else>{{nn.finishCount}} / {{nn.userCount}}</span>
              </div>
            </div>
          </div>
          <!-- <div class="weui-cell__ft weui-cell__ft_in-access avatars">
          </div> -->
        </div>
      </div>
    </div>
    <div v-if="pageInfo.hasMore" class="ta-c pdt">数据加载中...</div>
    <div v-if="pageInfo.totalPages > 1 && !pageInfo.hasMore" class="ta-c pdt-xxl c-gray">没有更多数据了！</div>
    <div v-if="isEmpty" class="ta-c pdt-xxl c-gray">这里还没有作业哦，点击屏幕下方『+』试试看！</div>
    <form report-submit @submit="onGoCreate">
      <button class="create-bar ui btn empty" formType="submit">
        <i class="if icon-add"></i>
      </button>
    </form>
    <page-common></page-common>
    <tab-bar></tab-bar>
    <div class="mask" v-show="firstLogin" @tap="closeMask">
      <div class="r-div">
        <image class="qipao" src="https://ark-1256750454.cos.ap-shanghai.myqcloud.com/app-statics/qipao.png" mode="widthFix"></image>
      </div>
    </div>
    <page-mask v-if="isPageLoading"></page-mask>
  </div>
</template>

<script>
import PageCommon from '@/components/page-common'
import PageMask from './page-mask'
import NotifyBtn from '@/components/notify-btn'
import NavBar from './nav-bar'
import { mapGetters, mapActions } from 'vuex'
import TabBar from '@/components/tab-bar'
import base from '@/mixins/base'
import dayjs from 'dayjs'
import * as $document from '@/api/document'
import * as $task from '@/api/task'
import * as _app from '@/utils/app'
import {taskGetMyCreates} from '@/graphql/task'
import {documentUnpublishes} from '@/graphql/document'
import * as _helper from '@/utils/helper'
export default {
  mixins: [base],
  data () {
    return {
      isPageNeedAuthUser: true,
      loaded: false,
      firstLogin: ''
    }
  },
  components: {
    PageCommon,
    TabBar,
    NavBar,
    NotifyBtn,
    PageMask
  },
  onLoad () {
    this.firstLogin = this.getParams().firstLogin
    // ***start***返回首页操作有关，参数从task invite 页传来
    let {forward, taskIds, taskId} = this.getParams()
    if (forward === 'document-forward' && taskIds) {
      wx.navigateTo({
        url: '/pages/document-forward/main?taskIds=' + taskIds
      })
    } else if (forward === 'task-progresses' && taskId) {
      wx.navigateTo({
        url: '/pages/task-progresses/main?taskId=' + taskId
      })
    }
    // ***end
  },
  onReachBottom () {
    if (!this.pageInfo.hasMore) return
    this.getMyCreatesByPage({
      type: this.navType,
      currentPage: this.pageInfo.currentPage + 1,
      cache: false
    })
  },
  async onPullDownRefresh() {
    try {
      await this.getUnpublishes()
      await this.getMyCreatesByPage({
        type: this.navType,
        currentPage: 1,
      })
      wx.stopPullDownRefresh()
    } catch (e) {
      this.$debug({err: e})
    }
  },
  computed: {
    ...mapGetters([
      'pageInfo'
    ]),
    ...mapGetters('task', [
      'tasks',
      'unreadCounts'
    ]),
    ...mapGetters('document', [
      'documents',
      'navType'
    ]),
    dateTasks () {
      let t = {}
      if (!this.tasks) return t
      for (var i = 0; i < this.tasks.length; i++) {
        let n = this.tasks[i]
        let date = this.navType === 'unpublished' ? n.prePublishAt : n.createdAt
        if (!date) continue
        date = dayjs(date).format('MM月DD日')
        t[date] = t[date] || []
        n.expireAtName = ''
        if (n.expireAt) {
          n.expireAtName = _helper.timeName(n.expireAt)
        }
        n.prePublishAtName = ''
        if (n.prePublishAt) {
          n.prePublishAtName = dayjs(n.prePublishAt).format('HH:mm')
        }
        if (n.group && n.group.name && n.group.name.length > 7) {
          n.group.name = n.group.name.substr(0, 7) + '...'
        }
        t[date].push(n)
      }
      return t
    },
    navTypeCurrent () {
      if (this.navType === 'published') return 0
      return 1
    },
    isEmpty () {
      if (this.documents.length === 0 && Object.keys(this.dateTasks).length === 0) return true
      return false
    }
  },
  onShareAppMessage() {
    return {
      title: this.document && this.document.name ? this.document.name : '',
      path: '/pages/index/main',
      imageUrl: ''
    }
  },
  methods: {
    ...mapActions([
      'setCurrentTab',
      'setBlocks',
    ]),
    onPageShow () {
      this.setCurrentTab('homework')
      this.isPageLoading = true
    },
    onPageHide () {
      this.isPageLoading = false
    },
    async loginBack () {
      try {
        if (this.tasks.length > 0) {
          this.isPageLoading = false
          return
        }
        await this.getMyCreatesByPage({
          type: this.navType,
          currentPage: 1
        })
        await this.getUnpublishes()
        this.isPageLoading = false
      } catch (e) {
        this.isPageLoading = false
        this.$debug({err: e})
      }
    },
    ...mapActions('document', [
      'updateName',
      'updateContent',
      'getUnpublishes'
    ]),
    ...mapActions([
      'setIsPageLoading'
    ]),
    ...mapActions('task', [
      'getMyCreatesByPage'
    ]),
    ...mapActions('notification', ['enqueue']),
    onGoCreate (e) {
      this.enqueue(e.target.formId)
      this.firstLogin = ''
      this.updateName('')
      this.updateContent('')
      this.$store.commit('document/DOCUMENT_SET_OPERATION', '')
      this.$store.commit('document/SET_DOCUMENT', {id: 0, name: '', data: { blocks: [] }, user: {id: 0, nickName: '', avatarUrl: ''}, t: new Date()})
      wx.navigateTo({
        url: '/pages/document-create/main'
      })
    },
    navChange (c) {
      if (c === 1) {
        this.$store.commit('document/DOCUMENT_SET_NAV_TYPE', 'unpublished')
      } else {
        this.$store.commit('document/DOCUMENT_SET_NAV_TYPE', 'published')
      }
    },
    onModify (n) {
      try {
        this.$store.commit('document/DOCUMENT_SET_OPERATION', '')
        this.$store.commit('document/SET_DOCUMENT', {...n, t: new Date()})

        this.updateName(n.name)

        let content = _app.getContentFromBlocks(n.data.blocks)
        this.updateContent(content)

        let mediaBlocks = _app.getMediaBlocksFromBlocks(n.data.blocks)
        this.setBlocks(mediaBlocks)

        wx.navigateTo({
          url: '/pages/document-create/main'
        })
      } catch (e) {
        this.$debug({err: e})
      }
    },
    closeMask () {
      this.firstLogin = false
    },
    goTaskProgresses (task) {
      this.$store.commit('document/DOCUMENT_SET_OPERATION', '')
      this.$store.commit('document/SET_DOCUMENT', {...task.document, t: new Date()})
      wx.navigateTo({
        url: '/pages/task-progresses/main?taskId=' + task.id
      })
    },
  },
  watch: {
    navType (nv) {
      this.getMyCreatesByPage({type: this.navType, currentPage: 1, cache: false})
    },
  }
}
</script>

<style scoped lang="less">
@import '../../assets/less/var.less';

.avatars {
  >div {
    line-height: 1;
    vertical-align: middle;
    display: inline-block;
    position: relative;
  }
}
.create-bar {
  display: block;
  position: fixed  !important;
  bottom: 70px  !important;
  right: 15px  !important;
  color: white !important;
  background: @colorTeal !important;
  height: 50px  !important;
  line-height: 1.4  !important;
  width: 50px !important;
  border-radius: 50% !important;
  text-align: center !important;
  box-shadow: 0 2px 20px 0 rgba(7,108,106,0.20);
  z-index:999;
  font-size: 3 * @baseSize !important;
  &:active {
    background: darken(@colorTeal, 10%) !important;
  }
  i {
    font-size: 18px;
    font-weight: bold;
  }
}
.mask{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,.5);
  z-index: 200;
}
.r-div{
  position: relative;
  width: 100%;
  height:100%;
}
.qipao{
  width:496rpx;
  position: absolute;
  bottom: 126rpx;
  right:12rpx;
}
.weui-cells:before{
  border-top:none;
}
.weui-cells:after{
  border-bottom:1rpx solid #eee;
  width: 100%;
  margin-left: 0;
}
</style>
